package emulator.GUI.keyboard;

import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;

import emulator.hardware.io.peripherals.Button;
import emulator.hardware.io.peripherals.Joystick;

public class VicKeyboardMap {
	private static final String SCANCODE = "scancode=";
	private VicKeyboard keyboard;
	private HashMap<String, String> key_map;
	private Joystick joystick;

	public VicKeyboardMap(VicKeyboard keyboard, Joystick joystick)
	{
		this.keyboard = keyboard;
		this.joystick = joystick;
		key_map = new HashMap<String, String>();
	}
	
	public boolean doKeyboardEvent(KeyEvent event)
	{
		int scan_code = getScanCodeFromKeyEvent(event);
		String key = "("+scan_code+","+event.getKeyLocation()+")";
		String key_name = key_map.get(key);
//		System.out.println("Key: "+key+" = "+key_name);
		if (key_name != null)
		{
			Button button = null;
			if (key_name.length() == 4 &&
					key_name.substring(0, 3).equalsIgnoreCase("joy"))
				button = joystick.getButton(key_name.charAt(3)-'0');
			else
				button = keyboard.getKey(key_name);
			if (button != null)
			{
				if (event.getID() == KeyEvent.KEY_PRESSED)
					button.press();
				else if (event.getID() == KeyEvent.KEY_RELEASED)
					button.release();
			}
		}
		return false;
	}

	private int getScanCodeFromKeyEvent(KeyEvent event) {
		String key_string = event.paramString();
		int scan_code_start = key_string.indexOf(SCANCODE);
		String scan_code = key_string.substring(scan_code_start + SCANCODE.length());
		return Integer.parseInt(scan_code);
	}
	
	public void save(OutputStream output_stream) {
		PrintStream out = new PrintStream(output_stream); 
		for (Map.Entry<String, String> key_info : key_map.entrySet())
		{
			out.println(key_info.getValue()+"="+key_info.getKey());
		}
	}
	
	public void load(InputStream input_stream) {
		key_map.clear();
		InputStreamReader reader = new InputStreamReader(input_stream);
	    BufferedReader in = new BufferedReader(reader);
	    String line = null;
	    try {
			while ((line = in.readLine()) != null)
			{
				if (line.length() == 0)
					continue;
				if (line.charAt(0) == ';')
					continue;
				int equal_pos = line.indexOf('=');
				if (equal_pos > 0)
				{
					String key_name = line.substring(0, equal_pos);
					String key = line.substring(equal_pos+1);
					key_map.put(key, key_name);
				}
				
			}
		} catch (IOException e) {
		}
	}
}
